package com.example.mobile203zlw20216061300514;

import android.os.Bundle;
import android.os.Trace;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private String news = "http://192.168.29.230:3000/news";
    private TextView mainText;
    private OkHttpClient okhttp=new OkHttpClient();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //刚开始线程
        new Thread(){
            @Override
            public void run() {
                Request request=new Request.Builder().url(news).build();//请求
                Call call=okhttp.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {//有响应
                        String tv=response.body().string();//把响应的转换成字符
                       runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                               mainText.setText(tv);
                           }
                       });
                    }
                });
            }
        }.start();
    }

    private void initView() {
        mainText = (TextView) findViewById(R.id.main_text);
    }
}